package net.pimpas.web.jsf.renderers.html.ajax;

import java.io.IOException;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.Renderer;

import net.pimpas.web.jsf.renderers.AjaxRendererBase;
import net.pimpas.web.jsf.renderers.RendererBase;
import net.pimpas.web.jsf.renderers.html.ajax.wrapper.AjaxHtmlResponseWriterWrapper;

import org.apache.myfaces.shared_impl.renderkit.RendererUtils;
import org.dom4j.Element;
import org.dom4j.Node;

public class AjaxHtmlRenderer extends RendererBase implements AjaxRendererBase {
	
	public static final String JAVASCRIPT_HANDLER		= "pimpas.AJAX.Populate.Html";
	
	
	@SuppressWarnings("unused")
	public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
		// wrapper the wrapper :-)
		AjaxHtmlResponseWriterWrapper wrapper = new AjaxHtmlResponseWriterWrapper(context.getResponseWriter());
		context.setResponseWriter(wrapper);
		
		ResponseWriter writer = wrapper.getResponseWriter();
		Renderer render 	= this.getRenderer(context, component);
		Renderer requals	= context.getRenderKit().getRenderer(component.getFamily(), component.getRendererType());
		// TODO what to do now?
		// i need get innerHTML from renderer, but how can i?!
		// normal
		writer.startElement("value", component);
		
		// wrapper
		wrapper.startElement("value", component);
		if(!requals.equals(render)) {
			render.encodeChildren(context, component);
			render.encodeEnd(context, component);
		} else {
			if(component.getRendersChildren())
				component.encodeChildren( context );
			else
				RendererUtils.renderChildren(context, component);
			component.encodeEnd(context);
		}
		//RendererUtils.renderChildren(context, component);
		// wrapper
		wrapper.endElement("value");
		
		context.setResponseWriter(wrapper.getResponseWriter());
		// now, get text element
		String txt = this.processHtmlText(wrapper);
		writer.write(txt);
		// normal
		writer.endElement("value");
	}
	
	public String processHtmlText(AjaxHtmlResponseWriterWrapper wrapper) {
		Element root = wrapper.getRoot();
		StringBuilder buff = new StringBuilder();
		
		for(int i=0;i<root.content().size();i++)
			buff.append(((Node)root.content().get(i)).asXML());
		
		return new String(buff);
	}

	public String getJavascriptHandler() {
		return JAVASCRIPT_HANDLER;
	}
	
	protected Renderer getRenderer(FacesContext context, UIComponent component ) {
		return context.getRenderKit().getRenderer(component.getFamily(), component.getRendererType());
	}

	public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
	}

	public void encodeChildren(FacesContext context, UIComponent component) throws IOException {
	}
}